#pragma once


#include <cstdlib>
#include <iostream>
#include <memory>
#include <utility>
#include <asio.hpp>
#include <mutex>
#include <unordered_map>
#include <vector>
#include <string>
#include <functional>
#include "channel.h"
#include "tcp_api.h"

class ChannelManager
{
public:
	ChannelManager():acceptor_(nullptr)
	{
		m_bAutoReLink = false;
	}

	~ChannelManager()
	{
		if (acceptor_) 
		{
			delete acceptor_;
		}
	}
	// 向所有服务发送数据
	bool SendToAllService(const char*pData, int nDataLen);
	// 向指定连接通道发送数据
	bool SendByChannelID(int nChannelID, const char*pData, int64_t nDataLen);
	void StartListen(int32_t port, CTcpSpi* pSvrSpi);
	void Stop();
	// 主动发起连接
	bool Connect(const std::string & strHost, int32_t iPort, CTcpSpi* pCliSpi, bool bAutoReLink = false);
	typedef std::vector<std::shared_ptr<Channel> > ChannelList;
	int AddService(std::shared_ptr<Channel> s);
	// 移除会话
	void DeleteService(std::shared_ptr<Channel> s);
	int32_t AddTimer(int id, int ms, mfvoid cb);
	void Timer(int id, int ms, mfvoid cb);
	int32_t RemoveTimer(int id);
private:
	void DoAccept();
	bool InternalConnect(const std::string & strHost, int32_t iPort);
	void DoConnect(asio::ip::tcp::socket *pConnectSocket, asio::ip::tcp::resolver::results_type *pEndPoint, 
							std::shared_ptr<asio::steady_timer> pTimer);
	void StartIoThread();
	//int m_nServerID;
	asio::io_context m_ioContext;
	asio::ip::tcp::acceptor *acceptor_;
	std::mutex m_ChannelsLock;
 	std::unordered_map<int, std::shared_ptr<Channel> > m_Channels;//客户端和服务端的channel都放入其中
	bool m_working;
	std::thread m_io_thread;
	CTcpSpi* m_pSvrSpi;
	CTcpSpi* m_pCliSpi;
	bool m_bAutoReLink;
	std::unordered_map<int32_t, std::shared_ptr<asio::steady_timer>> m_TimerMap;
	friend Channel;
};
